package cn.zyjblogs.starter.sms.core;


import cn.zyjblogs.starter.sms.common.SmsEnum;
import cn.zyjblogs.starter.sms.common.SmsRequest;
import cn.zyjblogs.starter.sms.common.SmsResponse;
import cn.zyjblogs.starter.sms.config.SmsProperties;
import cn.zyjblogs.starter.sms.exception.SmsRuntimeException;
import cn.zyjblogs.starter.sms.provider.SmsGranter;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

/**
 * @author zhuyijun
 */
@Component
public class SmsTemplate {
    private final SmsGranter smsGranter;
    private final List<SmsEnum> typeNames = new ArrayList<>();
    private final Random index = new Random();
    public SmsTemplate(SmsGranter smsGranter,SmsProperties smsProperties){
        this.smsGranter = smsGranter;
        typeNames.addAll(smsProperties.getAvailableSms());
    }

    /**
     * 短信发送 ，手机号为多个以逗号隔开
     *
     * @param phones
     * @param smsRequest
     * @return
     */
    public SmsResponse sendSms(List<String> phones, SmsRequest smsRequest){
        if (CollectionUtils.isEmpty(typeNames)){
            throw new SmsRuntimeException("没有配置短信，请检查配置");
        }
        return smsGranter.sendSms(getRandomSms(),phones,smsRequest);
    }

    public SmsEnum getRandomSms(){
        return typeNames.get(index.nextInt(typeNames.size()));
    }
    /**
     * 单笔短信发送
     *
     * @param phone
     * @param smsRequest
     * @return
     */
    public SmsResponse sendSms( String phone, SmsRequest smsRequest){
        return smsGranter.sendSms(getRandomSms(),phone,smsRequest);
    }

    /**
     * 短信发送 ，手机号为多个以逗号隔开
     *
     * @param typeName
     * @param phones
     * @param smsRequest
     * @return
     */
    public SmsResponse sendSms(SmsEnum typeName, List<String> phones, SmsRequest smsRequest){
        return smsGranter.sendSms(typeName,phones,smsRequest);
    }

    /**
     * 单笔短信发送
     *
     * @param typeName
     * @param phone
     * @param smsRequest
     * @return
     */
    public SmsResponse sendSms(SmsEnum typeName, String phone, SmsRequest smsRequest){
        return smsGranter.sendSms(typeName,phone,smsRequest);
    }
}
